<?php
namespace App\Http\Controllers;
/**
 * 
 * 购物车控制器
 * 
 * @author maqu
 *
 */

use App\Models\LandownersOrderEvaluation;
use App\Services\LandownersRefundService;
use App\Services\LandownersService;
use App\Services\OrderPingppService;
use App\Services\LandownersOrderService;
use App\Models\LandownersDeliver;
use App\Models\LandownersStatistics;
use App\Services\StoreService;
use App\Services\CommissionService;
use App\Services\UserAccountService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
use App\Services\LogisticsService;
use Illuminate\Support\Facades\Storage;

class LandownersOrderController extends BaseController {

    //可使用优惠券列表
//    public function listCoupon(){
//
//        $user_id = Input::get('user_id');
//        $amount=intval(Input::get('amount',0));//购物金额
//        $firstRow = Input::get('firstrow',0);
//        $pageSize = Input::get('pagesize',10);
//
//        $couponService = new CouponService();
//
//        $user_coupons=$couponService->getCashierCouponList($user_id,$amount,$firstRow,$pageSize);
//
//        return $this->success($user_coupons);
//    }

    //可使用配送方式列表
//    public function listShipping(){
//
//        $store_id = Input::get('stoer_id',1);
//        $firstRow = Input::get('firstrow',0);
//        $pageSize = Input::get('pagesize',10);
//
//        $cashierService = new CashierService();
//
//        /* 配送方式 */
//        $shippingList = $cashierService->getShippingList($store_id,$firstRow,$pageSize);
//        if (empty($shippingList))
//        {
//            return $this->failure ( '没有配送方式' );
//        }
//
//        return $this->success($shippingList);
//    }

//	public function initByCart(){
//
//		$user_id = Input::get('user_id');
//        $store_id = Input::get('store_id',1);
//
//        if(!$user_id){
//            return $this->args_invalid();
//        }
//
//        $userinfo = DB::table('member')->where('user_id',$user_id)->first();
//        if(!$userinfo){
//            return $this->failure("用户不存在");
//        }
//
//        if(empty($userinfo->user_name)){
//            return $this->need_bind();
//        }
//
//        $cashierService = new CashierService();
//
//        //获取购物信息
//		if(!Input::has('rec_ids')){//整个购物车购买
//	        $carts = $cashierService->getGoodsByCart($user_id,$store_id);
//	    }else{//购物车内部分购买
//	    	$rec_id_list=explode(",",Input::get('rec_ids'));
//
//            //判断购物车信息是否发生变化
//            $cartService = new CartService();
//            $cart = $cartService->getCartList($rec_id_list,$user_id);
//            if(count($cart) != count($rec_id_list)){
//                return $this->failure ( '购物车信息已发生改变' );
//            }
//            $carts = $cashierService->getGoodsByCart($user_id,$store_id,$rec_id_list);
//	    }
//
//        if(empty($carts)){
//            return $this->failure ( '购物车内没有商品' );
//        }
//
//        //编辑返回数据
//        $return = $carts;
//        $return['selected_rec_ids']=Input::get('rec_ids');
//        //获取默认地址
//        $address= DB::table('address')->where('user_id',$user_id)->where('is_default',1)->first();
//
//        if($address){
//		  $return['default_address'] = (array)$address;
//        }else {
//            $return['default_address'] = [];
//        }
//
////        /* 默认配送方式 */
////        $shipping_methods = $cashierService->getShippingMethods($store_id);
////        $return['default_shipping']          = $shipping_methods;
////
////        /* 配送费用=首件费用＋超出的件数*续件费用 */
////        if($shipping_methods){
////            $shipping_fee = $shipping_methods->first_price + ($carts['total_store']['quantity'] - 1) * $shipping_methods->step_price;
////        }else{
////            $shipping_fee = 0;
////        }
////        $return['default_shipping']->shipping_fee        = $shipping_fee;
//
//        //获取店铺配置
//        $storeService = new StoreService();
//        $storeConfig = $storeService->getStoreConfig($carts['store_info']['store_id']);
//
//        /* 配送费为固定设置 */
//        if($carts['total_store']['goods_amount'] < $storeConfig['shipping']['min_free']){
//            $shipping_fee = $storeConfig['shipping']['shipping_fee'];
//        }else{
//            $shipping_fee = 0;
//        }
//        $return['shipping_fee'] = $shipping_fee;
//
//        /* 默认使用快要过期的可用优惠券 */
//        $couponService = new CouponService();
//        $user_coupon=$couponService->getCashierCouponMethods($user_id,$carts['total_store']['goods_amount']);
//        $return['default_coupon'] = $user_coupon;
//        if($user_coupon){
//            $coupon_fee = $user_coupon['coupon_value'];
//        }else{
//            $coupon_fee = 0;
//        }
//
//        $return['sub_amount'] = $carts['total_store']['goods_amount'] + $shipping_fee - $coupon_fee;
//
//        //支付方式列表
//        $pay_list = [
//            [
//                'payment_id'   => 1,
//                'payment_name' => '支付宝',
//                'payment_code' => 'alipay'
//            ],
//            [
//                'payment_id'   => 2,
//                'payment_name' => '微信',
//                'payment_code' => 'wxPay'
//            ]
//        ];
//
//        $return['pay_list'] = $pay_list;
//
//	    return $this->success($return);
//	}

    /**
     *
     * 下单确认页面初始化
     *
     * @param GoodsService $goodsService
     * @param StoreService $storeService
     * @return mixed
     */
	public function initByLandowners(LandownersService $landownersService,StoreService $storeService){

		$user_id = Input::get('user_id');
        $spec_id = Input::get('spec_id');//套装商品规格id
		$quantity = Input::get('quantity',1);
        $addr_id = Input::get('addr_id',0);//地址
        $province = Input::get('province');//省

		if (!$spec_id || !$quantity || !$user_id)
        {
            return $this->failure('参数不对');
        }

        $userinfo = DB::table('member')->where('user_id',$user_id)->first();
        if(!$userinfo){
            return $this->failure("用户不存在");
        }

        //TODO
//        if(empty($userinfo->user_name)){
//            return $this->need_bind();
//        }

	    /* 是否有商品 */
        $spec_info = $landownersService->getGoodsSpec($spec_id);

        if (!$spec_info){
            return $this->failure('商品不存在');
        }

        if ($quantity > $spec_info->stock){
            return $this->failure('库存不足');
        }

        //编辑商品规格信息
        $spec_1 = $spec_info->spec_name_1 ? $spec_info->spec_name_1 . ':' . $spec_info->spec_1 : $spec_info->spec_1;
//        $spec_2 = $spec_info->spec_name_2 ? $spec_info->spec_name_2 . ':' . $spec_info->spec_2 : $spec_info->spec_2;
        if($spec_info->spec_name_1 && $spec_info->spec_name_2){
            $specification =  $spec_1 . ' ' . $spec_2;
        }elseif($spec_info->spec_name_1 && !$spec_info->spec_name_2 ){
            $specification =  $spec_1;
        }elseif($spec_info->spec_name_2 && !$spec_info->spec_name_1){
            $specification =  $spec_2;
        }else{
            $specification = "";
        }

//        $configs= json_decode($spec_info->config);
//        $config['shipping'] = (array)$configs->shipping;

        //编辑数据
        $temp = [
//            'store_info' => [
//                'store_id' => $spec_info->store_id,
//                'store_name' => $spec_info->store_name
//            ],
//            'total_store' => [
//                'goods_amount' => $spec_info->price*$quantity,
//                'quantity' => $quantity,
////                'shipping_fee_info' => "满".$config['shipping']['min_free']."元包邮,不足金额运费".$config['shipping']['shipping_fee']."元"
//            ],
//            'set_info' => [],
            'landowners'=>[],
        ];

        //组合商品子商品数据
//        $subgoods = [];
//        if($spec_info->is_set){
//            $subgoods = $goodsService->getSubGoods2([$spec_info->goods_id]);
//            $temp['set_info']['goods_id'] = $spec_info->goods_id;
//            $temp['set_info']['goods_name'] = $spec_info->goods_name;
//            $temp['set_info']['spec_id'] = $spec_info->spec_id;
//            $temp['set_info']['specification'] = $specification ;
//
//            /* 商品缩略图 */
//            empty($spec_info->default_image) && $spec_info->default_image = env('default_goods_image');
//            $temp['set_info']['goods_image'] = complete_url($spec_info->default_image);
//
//            $temp['set_info']['quantity'] = $quantity;
//            $temp['set_info']['price'] = $spec_info->price;
//            $temp['set_info']['stock'] = $spec_info->stock;
//            foreach($subgoods as $k => $goods){
//                //规格信息编辑
//                $temp_spec_1 = $goods->spec_name_1 ? $goods->spec_name_1 . ':' . $goods->spec_1 : $goods->spec_1;
//                $temp_spec_2 = $goods->spec_name_2 ? $goods->spec_name_2 . ':' . $goods->spec_2 : $goods->spec_2;
//                $temp_specification = $temp_spec_1 . ' ' . $temp_spec_2;
//
//                $temp['goods'][$k]['goods_id'] = $goods->goods_id;
//                $temp['goods'][$k]['goods_name'] = $goods->goods_name;
//                $temp['goods'][$k]['spec_id'] = $goods->spec_id;
//                $temp['goods'][$k]['specification'] = $temp_specification;
//                $temp['goods'][$k]['quantity'] = $quantity;
//                $temp['goods'][$k]['price'] = $goods->price;
//                $temp['goods'][$k]['stock'] = $goods->stock;
//                /* 商品缩略图 */
//                empty($goods->default_image) && $goods->default_image = env('default_goods_image');
//                $temp['goods'][$k]['goods_image'] = complete_url($goods->default_image);
//            }
//        }else{
            $temp['landowners'][0]['store_id'] = $spec_info->store_id;
            $temp['landowners'][0]['landowners_id'] = $spec_info->landowners_id;
            $temp['landowners'][0]['landowners_name'] = $spec_info->landowners_name;
            $temp['landowners'][0]['spec_id'] = $spec_info->spec_id;
            $temp['landowners'][0]['specification'] = $specification ;
            $temp['landowners'][0]['quantity'] = $quantity;
            $temp['landowners'][0]['price'] = $spec_info->price;
            $temp['landowners'][0]['market_price'] = $spec_info->market_price;
            $temp['landowners'][0]['stock'] = $spec_info->stock;
            $logistics = new LogisticsService();
            if($province){
                $region_id = DB::table('region')->where('region_name',$province)->value('region_id');
                $postage = $logistics->getLogisticsMoney($spec_info->landowners_id,$region_id,$quantity,'landowners');
                $temp['region'] = $province ;
                $temp['postage'] = $postage;
            }else{
                $postage = $logistics->getLogisticsMoney($spec_info->landowners_id,'',$quantity,'landowners');
                $temp['region'] = $province ;
                $temp['postage'] = $postage;
            }

            /* 商品缩略图 */
//            empty($spec_info->default_image) && $spec_info->default_image = env('default_goods_image');
//            $temp['goods'][0]['goods_image'] = complete_url($spec_info->default_image);

            empty($spec_info->default_image) && $spec_info->default_image = env('default_goods_image');
            $temp['landowners'][0]['landowners_image'] = complete_url($spec_info->default_image);
//            dd($temp);

//        }

        //获取默认地址
        $address= null;
        if($addr_id){
            $address= DB::table('address')->where('user_id',$user_id)->where('addr_id',$addr_id)->first();
        } else {
            $address= DB::table('address')->where('user_id',$user_id)->where('is_default',1)->first();
        }

        //编辑返回值
        $return = $temp;

        if($address){
            $return['default_address'] = (array)$address;
        }else {
            $return['default_address'] = [];
        }

//        /* 配送方式 */
//        $cashierService = new CashierService();
//        /* 默认配送方式 */
//        $shipping_methods = $cashierService->getShippingMethods($store_id);
//        $return['default_shipping']          = $shipping_methods;

//        /* 配送费用=首件费用＋超出的件数*续件费用 */
//        if($shipping_methods){
//            $shipping_fee = $shipping_methods->first_price + ($temp['total_store']['quantity'] - 1) * $shipping_methods->step_price;
//        }else{
//            $shipping_fee = 0;
//        }

        //获取店铺配置
//        $storeConfig = $storeService->getStoreConfig($spec_info->store_id);

        /* 配送费为固定设置 */
//        if($temp['total_store']['goods_amount'] < $storeConfig['shipping']['min_free']){
//            $shipping_fee = $storeConfig['shipping']['shipping_fee'];
//        }else{
            $shipping_fee = 0;
//        }
        $return['shipping_fee'] = $shipping_fee;

//        /* 默认使用快要过期的可用优惠券 */
//        $couponService = new CouponService();
//        $user_coupon = $couponService->getCashierCouponMethods($user_id,$temp['total_store']['goods_amount']);
//        $return['default_coupon'] = $user_coupon;
//        if($user_coupon){
//            $coupon_fee = $user_coupon['coupon_value'];
//        }else{
            $coupon_fee = 0;
//        }

        $return['sub_amount'] = $spec_info->price*$quantity + $shipping_fee - $coupon_fee;

        return $this->success($return);
	}
    /**
     * 订单列表
    */
    public function lists($user_id){
        $firstrow = Input::get('firstrow',0);
        $pagesize = Input::get('pagesize',10);
        $nav = Input::get('nav','all');
        if($user_id == ''){
            return $this->failure("参数错误");
        }
        $user_result = DB::table('member')->where('user_id',$user_id)->first();
        if(!$user_result){
            return $this->failure("该用户不存在");
        }

        $landowners_service = new LandownersOrderService();
        $data = $landowners_service->deliver_list($user_id,$nav,$firstrow,$pagesize);
        /* 编辑返回数据 */
        $return = [];
        /* 编辑订单数据 */
        foreach($data as $k => $order){

            $order_arr = [
                "order_id" => $order['order_id'],
                "order_sn" => $order['order_sn'],
                "order_name" =>'',
                "seller_id" => $order['seller_id'],
                "seller_name" => $order['seller_name'],
                "extension"  => $order['extension'],
                "status" => $order['status'],
                "status_name" => '',
                "landowners_detail" => '',
                "landowners_amount" => $order['landowners_amount'],
                "shipping_fee" => $order['order_extm']['shipping_fee'],
                "discount" => $order['discount'],
                "order_amount" => $order['order_amount'],
                "add_time" => local_date('Y-m-d H:i:s',$order['add_time']),
                "shipping_name" => $order['order_extm']['shipping_name'],
                "shipping_egname" =>$this->getShippingEg($order['order_extm']['shipping_name']) ,
                "invoice_no" => $order['invoice_no'],
                "landowners_count" => 0,
                "refund_status" => 0,
                "landowners_order" => [],
                "ican" => [
                    "payment" => false,
                    "cancel" => false,
                    "delete" => false,
                    "confirm_order" => false,
                    "view_logistics" => false,
                    "evaluate" => false,
                ],
                "tuan_state" => -1,
                "share_tuan" => [
                    "share_tuan_desc" => "",
                    "share_tuan_url" => "",
                ]

            ];

            /* 退款/货商品数据编辑处理 */
            $refund_landowners_arr = [];
            if(count($order['landowners_refund_goods'])>0){
                foreach($order['landowners_refund_goods'] as $i => $refund_landowners){
                    $refund_landowners_arr[$refund_landowners['spec_id']] = $refund_landowners;
                }
            }

            /* 退款/货单数据编辑处理 */
            $order_refund_arr = [];
            if(count($order['landowners_refund'])>0){
                foreach($order['landowners_refund'] as $i => $order_refund){
                    $order_refund_arr[$order_refund['refund_id']] = $order_refund;
                }
            }

            $landowners_count = 0;
            $detail = '';
            /* 编辑订单商品信息 */
            foreach ($order['landowners_order_evaluation'] as $i => $order_landowners){
                $order_landowners_arr = [
                    "rec_id" => $order_landowners['rec_id'],
                    "landowners_id" => $order_landowners['landowners_id'],
                    "landowners_name" => $order_landowners['landowners_name'],
                    "spec_id" => $order_landowners['spec_id'],
                    "specification" => $order_landowners['specification'],
                    "price" => $order_landowners['price'],
                    "market_price" => $order_landowners['market_price'],
                    "quantity" => $order_landowners['quantity'],
                    "gstatus_name" => "",
                    "landowners_image" => "",
						"orderGoodsIcan" => [
								"apply_refund" => false,
								"cancel_refund" => false,
								"return_goods" => false,
								"change_expressno" => false,
						]
                ];

                /* 商品总数 */
                $landowners_count += $order_landowners['quantity'];

                /* 商品状态 */
                $landowners_status =  0;
                if(array_key_exists($order_landowners['spec_id'],$refund_landowners_arr)){
                    $order_landowners_arr['gstatus_name']
                        = $landowners_service->orderLandownersStatus(
                        $order_refund_arr[$refund_landowners_arr[$order_landowners['spec_id']]['refund_id']]['refund_type'],
                        $order_refund_arr[$refund_landowners_arr[$order_landowners['spec_id']]['refund_id']]['refund_status']);

                    $landowners_status = $order_refund_arr[$refund_landowners_arr[$order_landowners['spec_id']]['refund_id']]['refund_status'];
                }

                //判断是否为售后订单
                if($landowners_status != LANDOWNERS_ORDRE_CANCELED && $landowners_status != LANDOWNERS_ORDRE_REFUND){
                    $order_arr['refund_status'] = 1;
                }

//				/* 商品可操作按钮 */
//				$order_goods_arr['orderGoodsIcan'] = $orderService->orderGoodsIcan($order['status'],$goods_status);

                /* 商品图片地址编辑 */
                if(!empty($order_landowners['landowners_image'])){
                    $order_landowners_arr['landowners_image'] = complete_url($order_landowners['landowners_image']);
                }
                /* 订单详情 */
                $detail .= $order_landowners['landowners_name'] . ' + ';

                /* 订单名称（默认为单类商品订单） */
                $order_arr['order_name'] = $order_landowners['landowners_name'];

                /* 编辑订单商品数据进入订单数据 */
                $order_arr['landowners_order'][] = $order_landowners_arr;

                unset($order_landowners_arr);
            }

            /* 订单内商品总数 */
            $order_arr['landowners_count'] = $landowners_count;


            switch ($order['extension']){
                case 'normal':

                    /* 订单名称（如果是多商品订单，显示名称为多商品购买） */
                    if(count($order['landowners_order_evaluation'])>1){
                        $order_arr['order_name'] = '多商品购买';
                    }

                    /* 订单名称详情（使用情景：多类商品订单中） */
                    $order_arr['landowners_detail'] = substr($detail, 0, -1);

                    /* 普通订单状态名 */
                    $order_arr['status_name'] = $landowners_service->orderStatus($order['status'],$order['evaluation_status'],$order['complain_status'],$order['order_id']);
                    $order_arr['ican'] = $landowners_service->orderIcan($order);
                    break;
            }

            if($order_arr['refund_status'] == 1){
                $order_arr['status_name'] = '退款退货中';
            }

            $return[] = $order_arr;
            unset($refund_goods_arr);
            unset($order_refund_arr);
            unset($order_arr);
        }
        return $this->success($return);
    }
    /**
     * 订单详情
     */
    public function detail($user_id,$order_id){

        if(!$user_id || !$order_id){
            return $this->failure("参数错误");
        }
        $landowners_order_service = new LandownersOrderService();
        $landowners_order_info = $landowners_order_service->getOrderInfo($user_id,$order_id);
        $order_info = $landowners_order_info->toArray();
        foreach($order_info['landowners_deliver'] as $key=>$value){
            $order_info['landowners_deliver'][$key]['shipping_egname']= $this->getShippingEg($value['shipping_name']);//获取快递对应的英文名用于调用快递100接口
        }
        $time = DB::table('config')->where('code','order_info_live_time_landowner')->value('value');//未支付订单存活时间商品 配置
        $order_arr = [
            "order_id" => $order_info['order_id'],
            "order_sn" => $order_info['order_sn'],
            "seller_id" => $order_info['seller_id'],
            "seller_name" => $order_info['seller_name'],
            "order_name" => '',
            "extension"  => $order_info['extension'],
            "status"	=> $order_info['status'],
            "status_name" =>'',
            "status_detail" => '',
            "landowners_detail" => '',
            "shipping_name" => $order_info['order_extm']['shipping_name'],
            "shipping_egname" =>$this->getShippingEg($order_info['order_extm']['shipping_name']) ,
            "invoice_no" => $order_info['invoice_no'],
            "evaluation_status" =>  $order_info['evaluation_status'],
            "landowners_amount" => $order_info['landowners_amount'],
            "discount" => $order_info['discount'],
            "order_amount" => $order_info['order_amount'],
            "add_time" => local_date('Y-m-d H:i:s',$order_info['add_time']),
            "end_time" => $order_info['add_time'] + $time*60 - gmtime(), //到期时间(秒)
            "pay_time"=> local_date('Y-m-d H:i:s',$order_info['pay_time']),
            "postscript" => $order_info['postscript'],
//            "goods_count" => 0,
            "refund_status" => 0,
//            "tuan_id" => $order_info['tuan_id'],
//            "pintuan_id" => $order_info['pintuan_id'],
            "order_extm" =>$order_info['order_extm'],
            'landowners_deliver'=>$order_info['landowners_deliver'],
            "landowners_order" => [],
            "coupon_info" => [
                'coupon_name' => '',
                'coupon_value' => 0,
            ],
            "complain"=>[],
            "groupbuy" => [],
            "ican" => [
                "payment" => false,
                "cancel" => false,
                "delete" => false,
                "confirm_order" => false,
                "view_logistics" => false,
                "evaluate" => false,
            ],
        ];

        //是否投诉
        if($order_info['complain_status'] == 1){
            $complain = DB::table('complain')->where('product_type','landowners')->where('order_id',$order_info['order_id'])->first();

            if($complain->pictures && count($complain->pictures)>0){
                $images = json_decode($complain->pictures,true);
            }
            if (is_array($images) && count($images)>0)
            {
                foreach($images as $image){
                    $imagearr[] = complete_url($image);
                }
                $complain->pictures = $imagearr;
            }else{
                $complain->pictures = '';
            }
            $complain->create_at = local_date_ymd($complain->create_at);
            $complain->update_at = local_date_ymd($complain->update_at);
            $order_arr['complain'] = $complain;
        }else{
            $order_arr['complain'] = '';
        }
        /* 退款/货商品数据编辑处理 */
        $refund_landowners_arr = [];
        if(count($order_info['landowners_refund_goods'])>0){
            foreach($order_info['landowners_refund_goods'] as $i => $refund_landowners){
                $refund_landowners_arr[$refund_landowners['spec_id']] = $refund_landowners;
            }
        }
        /* 退款/货单数据编辑处理 */
        $order_refund_arr = [];
        if(count($order_info['landowners_refund'])>0){
            foreach($order_info['landowners_refund'] as $i => $order_refund){
                $order_refund_arr[$order_refund['refund_id']] = $order_refund;
            }
        }
        $landowners_count = 0;
        $detail = '';
        /* 编辑订单商品信息 */
        foreach ($order_info['landowners_order_evaluation'] as $i => $order_landowners) {
            $order_landowners_arr = [
                "rec_id" => $order_landowners['rec_id'],
                "landowners_id" => $order_landowners['landowners_id'],
                "landowners_name" => $order_landowners['landowners_name'],
                "spec_id" => $order_landowners['spec_id'],
                "specification" => $order_landowners['specification'],
                "market_price" => $order_landowners['market_price'],
                "price" => $order_landowners['price'],
                "quantity" => $order_landowners['quantity'],
                "gstatus_name" => "",
                "landowners_image" => $order_landowners['landowners_image'],
                "orderLandownersIcan" => [
                    "apply_refund" => false,
                    "cancel_refund" => false,
                    "return_landowners" => false,
                    "change_expressno" => false,
                ]
            ];
            /* 总数 */
            $landowners_count += $order_landowners['quantity'];
            if(array_key_exists($order_landowners['spec_id'],$refund_landowners_arr)){
                $order_landowners_arr['gstatus_name']
                    = $landowners_order_service->orderLandownersStatus(
                    $order_refund_arr[$refund_landowners_arr[$order_landowners['spec_id']]['refund_id']]['refund_type'],
                    $order_refund_arr[$refund_landowners_arr[$order_landowners['spec_id']]['refund_id']]['refund_status']);

                $landowners_status = $order_refund_arr[$refund_landowners_arr[$order_landowners['spec_id']]['refund_id']]['refund_status'];
            }
            //判断是否为售后订单
            if(isset($landowners_status) && $landowners_status != REFUND_CANCELED && $landowners_status != REFUND_FINISHED){
                $order_arr['refund_status'] = 1;
            }
            /* 做地主可操作按钮 */
            $order_landowners_arr['orderLandownersIcan'] = $landowners_order_service->orderLandownersIcan($order_info['extension'],$order_info['status'],isset($landowners_status) ? $landowners_status : '');
            if(!empty($order_landowners['landowners_image'])){
                $order_landowners_arr['landowners_image'] = complete_url($order_landowners['landowners_image']);
            }
            /* 订单详情 */
            $detail .= $order_landowners['landowners_name'] . ' + ';
            /* 订单名称（默认为单类商品订单） */
            $order_arr['order_name'] = $order_landowners['landowners_name'];
            /* 编辑订单数据进入订单数据 */
            $order_arr['order_landowners'][] = $order_landowners_arr;
            unset($refund_landowners_arr);
        }

//        if($order_info['extension'] == 'normal'){
//            /* 订单名称（如果是多商品订单，显示名称为多商品购买） */
//            if(count($order_info['landowners_order_evaluation'])>1){
//                $order_arr['order_name'] = '多商品购买';
//            }
//
//            /* 订单名称详情（使用情景：多类商品订单中） */
//            $order_arr['goods_detail'] = substr($detail, 0, -1);
//
            /* 普通订单状态名 */
            $order_arr['status_name'] = $landowners_order_service->orderStatus($order_info['status'],$order_info['evaluation_status'],$order_info['complain_status'],$order_info['order_id']);
            $order_arr['ican'] = $landowners_order_service->orderIcan($order_info);
//        }
        if($order_arr['refund_status'] == 1){
            $order_arr['status_name'] = '退款退货中';
            $order_arr['status_detail'] = '正在为您处理中，请耐心等待';
        }
        unset($refund_landowners_arr);
        unset($order_refund_arr);
        //支付方式列表
        $pay_list = [
            [
                'payment_id'   => 1,
                'payment_name' => '支付宝',
                'payment_code' => 'alipay',
                'chosed'	   => 0,
            ],
            [
                'payment_id'   => 2,
                'payment_name' => '微信',
                'payment_code' => 'wxPay',
                'chosed'	   => 0,
            ]
        ];
        foreach($pay_list as $k =>$item){
            if($item['payment_id'] == $order_info['payment_id']){
                $pay_list[$k]['chosed'] = 1;
            }
        }
        $order_arr['pay_list'] = $pay_list;
        return $this->success($order_arr);

    }

    public function confirm($user_id,$order_id){

        $user_info = DB::table('member')->where('user_id',$user_id)->first();
        if(!$user_info){
            return $this->failure("该用户不存在");
        }
        $landowners_service = new LandownersOrderService();
        $landowners_order_info = $landowners_service->getOrderInfo($user_id,$order_id);
        if (empty($landowners_order_info)){
            return $this->failure('参数不对');
        }
        if($landowners_order_info->status!=LANDOWNERS_ORDRE_SHIPPED ){ //订单不是待收货 无法确认收货
            return $this->failure('该订单无法确认收货');
        }

        if(count($landowners_order_info->landownersRefund)>0){
            foreach($landowners_order_info->landownersRefund as $k => $item){
                if($item->refund_status != LANDOWNERS_ORDRE_REFUND && $item->refund_status != LANDOWNERS_REFUND_CANCELED ){
                    return $this->failure('该订单有商品处于退货中，无法确认收货');
                }
            }
        };
        $deliver_result = LandownersDeliver::where('deliver_id',$landowners_order_info->deliver_id)->first();
        if($deliver_result->status==1){
            return $this->failure('此次流程已完成');
        }

        DB::beginTransaction();
        try {
            /* 更新订单状态 */
            DB::table('landowners_order')
                ->where('order_id',$order_id)
                ->update([
                    'status' => LANDOWNERS_ORDRE_FINISHED,//已完成
                    'finished_time' => gmtime()
                ]);

            /* 操作记录 */
                //更新对应发货单状态
                DB::table('landowners_deliver')
                    ->where('deliver_id',$landowners_order_info->deliver_id)
                    ->update([
                        'status' =>1, //单次收货完成
                        'take_time' => gmtime()
                    ]);
                //更新订单操作日志
            $landowners_service->addLandownersOrderLog($order_id,$user_id,LANDOWNERS_ORDRE_SHIPPED,LANDOWNERS_ORDRE_FINISHED,'用户确认收货',$landowners_order_info->deliver_id,'');

                //判断订单是否全部发货 获取已发货并完成的次数
                $count_deliver = DB::table('landowners_deliver')
                    ->where('order_id',$order_id)
                    ->where('status',1)
                    ->count();
                //如果发货次数不足修改订单状态进行下次发货
                if($count_deliver < $landowners_order_info->deliver_count) {
                    /* 更新订单状态 */
                    DB::table('landowners_order')
                        ->where('order_id', $order_id)
                        ->update([
                            'status' => LANDOWNERS_ORDER_ACCEPTED,//待发货
                            'finished_time' => gmtime(),
                        ]);
                    //更新订单操作日志
                    $landowners_service->addLandownersOrderLog($order_id, $user_id, LANDOWNERS_ORDRE_FINISHED, LANDOWNERS_ORDER_ACCEPTED, '用户完成单次流程,进入下次流程', '', '');
                }elseif($count_deliver == $landowners_order_info->deliver_count){ //货已发完计算收益
                    //用户确认收货收益计算
                    $commission = new CommissionService();
                    $user_account = new UserAccountService();
                    $account_money = $commission->getCommission($landowners_order_info->seller_id,$landowners_order_info->order_amount,'landowners');

                    //平台收益
                    $admin_commission = $account_money['franchisee_commission_goods']; //平台收益比例
                    $admin_money = 	$account_money['admin_money'];

                    //加盟商收益
                    $franchisee_commission = $account_money['partner_commission']; //加盟商收益比例
                    $franchisee_money = $account_money['franchisee_money'];

                    //合伙人收益
                    $partner_money = $account_money['partner_money'];

                    //账户资金操作  以及记录日志
                    if($admin_money > 0 ){
                        $user_account->incomeMoney(1,$admin_money,'结算做地主订单:订单编号:'.$landowners_order_info->order_sn.'分成比例:'.$admin_commission.'%',$landowners_order_info->order_id,'landowners','+');
                    }

                    if($franchisee_money > 0 && $account_money['franchisee_id'] > 0){
                        $user_account->incomeMoney($account_money['franchisee_id'],$franchisee_money,'结算做地主订单:订单编号:'.$landowners_order_info->order_sn.'分成比例:'.$franchisee_commission.'%',$landowners_order_info->order_id,'landowners','+');
                    }

                    if($partner_money > 0){
                        $user_account->incomeMoney($landowners_order_info->seller_id,$partner_money,'结算做地主订单:订单编号:'.$landowners_order_info->order_sn.'',$landowners_order_info->order_id,'landowners','+');
                    }
                    //获取购买数量更新销量
                    $count_deliver = DB::table('landowners_deliver')
                        ->where('order_id',$order_id)
                        ->where('status',1)
                        ->count();
                    //订单完成更新销量
                    DB::table('landowners_statistics')
                        ->leftjoin('landowners_deliver','landowners_deliver.landowners_id','=','landowners_statistics.landowners_id')
                        ->where('landowners_deliver.order_id',$order_id)
                        ->increment('sales',$count_deliver);
                }

            DB::commit();

            return $this->success(null);

        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }

    //买家-退款申请
    /**
     * 申请退款
     *
     * @param $user_id：用户id
     * @param $order_id：订单id
     *
     */
    public function getApplyRefund($user_id,$order_id){

        if(!$order_id){
            return $this->failure('参数不对');
        }

        $orderService = new LandownersOrderService();
        $orderInfo = $orderService->getOrderInfo($user_id,$order_id);

        //判断订单是否存在
        if(!$orderInfo){
            return $this->failure('订单不存在');
        }
        //订单状态不是待发货或者待收货，不可以提交退款/货申请
        if(!($orderInfo->status == LANDOWNERS_ORDER_ACCEPTED || $orderInfo->status == LANDOWNERS_ORDRE_SHIPPED )){
            return $this->failure('该订单不可退款/货');
        }

        //判断订单商品是否存在
        $spec_id = 0;
        foreach($orderInfo->landownersOrderEvaluation as $order_goods){
            if($order_goods->order_id == $order_id){
                $spec_id = $order_goods->spec_id;
                break;
            }
        }
        if(!$spec_id){
            return $this->failure('订单商品不存在');
        }

        //判断该商品是否已经处于退款/货流程中了
        $refund_id = 0;
        if($orderInfo->landowners_refund_goods){
            foreach($orderInfo->landowners_refund_goods as $refund_goods){
                if($refund_goods->spec_id == $spec_id){
                    $refund_id = $refund_goods->refund_id;
                    break;
                }
            }
        }
        if($refund_id){
            foreach($orderInfo->landowners_refund as $order_refund){
                if($order_refund->refund_id == $refund_id){
                    if($order_refund->refund_status != LANDOWNERS_REFUND_CANCELED){
                        return $this->failure('请不要重复申请');
                    }
                }
            }
        }

        $reasons = [
            '订单信息有误/拍错-（未发货）',
            '未收到货',
            '商品质量问题',
            '商品漏发错发',
            '商品与描述不一致',
            '其他'
        ];

        $result =[
            'reasons' =>$reasons,
            'max_refund_amount' => $orderInfo->order_amount,
        ];

        return $this->success($result);
    }

    //买家提交退款/货申请
    /**
     * 退款
     *
     * @param $rec_id：订单商品id
     */
    public function postApplyRefund($user_id,$order_id){

        //获取页面传递的数据
        $refund_type = Input::get('refund_type',REFUND_TYPE_REFUND);//退款/货类型 1 退款 2 退货
        $refund_reason	= Input::get('refund_reason');//退款理由
        $refund_amount	= Input::get('refund_amount');//退款金额
        $refund_desc	= Input::get('refund_desc');//退款说明

        if(!$order_id||!$user_id||!$refund_type||!$refund_reason||!$refund_amount){
            return $this->failure('参数不对');
        }

        $orderService = new LandownersOrderService();
        $orderInfo = $orderService->getOrderInfo($user_id,$order_id);

        //判断订单是否存在
        if(!$orderInfo){
            return $this->failure('订单不存在');
        }
        //订单状态不是待发货且不是退款或者待收货且不是退货，则不可以提交退款/货申请
        if(!($orderInfo->status == LANDOWNERS_ORDER_ACCEPTED || $orderInfo->status == LANDOWNERS_ORDRE_SHIPPED )){
            return $this->failure('该订单不可退款/货');
        }

        if($orderInfo->status == LANDOWNERS_ORDER_ACCEPTED && $refund_type != REFUND_TYPE_REFUND){
            return $this->failure('该订单不可申请退货');
        }

        if($orderInfo->status == LANDOWNERS_ORDRE_SHIPPED && $refund_type != REFUND_TYPE_RETURN_GOODS){
            return $this->failure('该订单不可申请退款');
        }

        //判断订单商品是否存在
        $spec_id = 0;
        $orderGoods = null;
        foreach($orderInfo->landownersOrderEvaluation as $order_goods){
            if($order_goods->order_id == $order_id){
                $spec_id = $order_goods->spec_id;
                break;
            }
        }
        if(!$spec_id){
            return $this->failure('订单商品不存在');
        }

        //判断该商品是否已经处于退款/货流程中了
        $refund_id = 0;
        if($orderInfo->landowners_refund_goods){
            foreach($orderInfo->landowners_refund_goods as $refund_goods){
                if($refund_goods->spec_id == $spec_id){
                    $refund_id = $refund_goods->refund_id;
                    break;
                }
            }
        }
        if($refund_id){
            foreach($orderInfo->landowners_refund as $order_refund){
                if($order_refund->refund_id == $refund_id){
                    if($order_refund->refund_status != LANDOWNERS_REFUND_CANCELED){
                        return $this->failure('请不要重复申请');
                    }
                }
            }
        }

        if($refund_amount > $orderInfo->order_amount){
            return $this->failure("退款金额不能大于该商品总金额");
        }
        DB::beginTransaction();

        try{
            $user_info = DB::table('member')->where('user_id',$user_id)->first();
            $user_name = $user_info->user_name;

            //添加或者更新退款/货申请
            $refundService = new LandownersRefundService();
            $refundService->addRefund($refund_id,$user_id,$refund_type,$refund_reason,$refund_amount,$refund_desc,$orderInfo);

            //添加退款流程操作记录
            $remark = '退款理由：'.$refund_reason.'退款说明：'.$refund_desc;
            $refundService->addOrderRefundLog($refund_id,$user_name,$refund_type,null,REFUND_PENDING,$remark);

            DB::table('landowners_order')
                ->where('order_id',$order_id)
                ->update([
                    'status' => LANDOWNERS_ORDER_REFUNDING,// 退款申请
                ]);

            /* 操作记录 */
            $orderService->addLandownersOrderLog($order_id,$user_name,LANDOWNERS_ORDER_ACCEPTED,LANDOWNERS_ORDER_REFUNDING,'用户申请退款',$orderInfo->deliver_id,'');
            DB::commit();
            return $this->success(null);
        } catch(Exception $e){
            DB::rollback();
            throw $e;
        }
    }
	
	public function createOrderByLandowners(){
	
	 	//**参数验证**
	    if(!Input::has('addr_id')){
	        return $this->failure('请选择收货地址');
	    }

//	    if(!Input::has('payment_id')){
//	        return $this->failure('请选择支付方式');
//	    }

//        if(!Input::has('shipping_id')){
//            return $this->failure('请选择配送方式');
//        }

        if(!Input::has('quantity')){
            return $this->failure('请选择购买数量');
        }

		$user_id = Input::get('user_id');
		$userinfo = DB::table('member')->where('user_id',$user_id)->first();
		if(!$userinfo){
		    return $this->failure("用户不存在");
		}

        //TODO 是否要绑定手机后才能使用
//        if(empty($userinfo->user_name)){
//            return $this->need_bind();
//        }

//		$store_id = Input::get('store_id');
//		$storeinfo = DB::table('store')->where('store_id',$store_id)->get();
//		if(!$storeinfo){
//		    return $this->failure("超市不存在");
//		}

		$spec_id = Input::get('spec_id');
        $quantity = Input::get('quantity',1);

        $orderService = new LandownersOrderService();
		$landowners_info = $orderService->getSingleLandownersInfo($spec_id,$quantity);


        if ($landowners_info === false)
        {
            /* 购物车是空的 */
            return $this->failure('商品已下架');
        }

        /*  检查库存 */
        $landowners_beyond = $orderService->checkBeyondStock($landowners_info['items']);

        if ($landowners_beyond)
        {
            return $this->failure('库存不足',$landowners_beyond);
        }

		/* 在此获取生成订单的两个基本要素：用户提交的数据（POST），商品信息（包含商品列表，商品总价，商品总数量，类型），所属店铺 */

        DB::beginTransaction();

        try {
            /* 优惠券数据处理 */
//            $coupon_type = Input::get('coupon_type','coupon');
//            $coupon_sn = Input::get('coupon_sn',0);
//            if ($goods_info['allow_coupon'] && $coupon_type && $coupon_sn)
//            {
//                if(!in_array($coupon_type, array('coupon','cashcoupon'))){
//                    return $this->failure('参数不对');
//                }
//                $coupon_info = [];
//                if($coupon_type=='coupon') {
//                    $couponService = new CouponService();
//                    $coupon_info = $couponService->getCouponInfo($coupon_sn);
//                } /*else {
//                    $coupon_info = DB::table('cash_coupon_sn')->join('cash_coupon','cash_coupon_sn.coupon_id','=','cash_coupon.coupon_id')
//                        ->where('cash_coupon.store_id',$store_id)->where('cash_coupon_sn.coupon_sn',$coupon_sn)
//                        ->select('cash_coupon.*','cash_coupon_sn.remain_times')->first();
//                }   */
//
//
//                if (empty($coupon_info)){
//                    return $this->failure('无效的优惠券编号');
//                }
//
//                $coupon_info = $coupon_info->toArray();
//
//                if ($coupon_info['remain_times'] < 1){
//                    return $this->failure('该优惠券已被使用');
//                }
//                $time = gmtime();
//                if ($coupon_info['coupon']['start_time'] > $time){
//                    return $this->failure('该优惠券尚不能使用');
//                }
//
//                if ($coupon_info['coupon']['end_time'] < $time)
//                {
//                    return $this->failure('该优惠券已过期');
//                }
//                if ($coupon_info['coupon']['min_amount'] > $goods_info['amount'])
//                {
//                    return $this->failure('未达到使用金额');
//                }
//                unset($time);
//                $goods_info['discount'] = $coupon_info['coupon']['coupon_value'];
//                $goods_info['coupon_sn'] = $coupon_sn;
//            }

            $order_sn = $orderService->getOrderSn();

            /* 将这些信息传递给订单类型处理类生成订单(你根据我提供的信息生成一张订单) */
            $submit = $orderService->submitOrder(array(
                'landowners_info'    =>  $landowners_info,        //商品信息（包括列表，总价，总量，所属店铺，类型）,可靠的!
                'post'          =>  Input::all(),       //用户填写的订单信息
                'order_sn'      =>  $order_sn           //订单号

            ));

            if (!$submit['order_id'])
            {
                DB::rollback();
                return $this->failure($submit['error']);
            }

            $order_id = $submit['order_id'];

            //减去优惠券使用次数
//            DB::table('coupon_sn')->where('coupon_sn',$coupon_sn)->decrement('remain_times',1);

            /* 更新下单次数 */
            $landowners_ids = array();
            foreach ($landowners_info['items'] as $landowners)
            {
                $landowners_ids[] = $landowners['landowners_id'];
            }

            DB::table('landowners_statistics')->whereIn('landowners_id',$landowners_ids)->increment('orders');

            DB::commit();

            $order_info = DB::table('landowners_order')->where('order_id',$order_id)->where('buyer_id',$user_id)->get();

        	if (empty($order_info))
        	{
            	return $this->failure('没有该订单');
        	}

        	$order_info = current($order_info);

        	$landowners_goods = DB::table('landowners_order_evaluation')->where('order_id',$order_id)->get();


            if(empty($landowners_goods)){
            	return $this->failure('订单中没有商品');
            }

            $landownersgoods = current($landowners_goods);
            $order_name = $landownersgoods->landowners_name;
            $landowners_detail = $landownersgoods->landowners_name;

	        /* 订单有效性判断 */
//	        if ($order_info->payment_code != 'cod'
//                && $order_info->status !=ORDER_PENDING
//                && $order_info->status != ORDER_ACCEPTED){
//	            return $this->failure('订单不可支付');
//	        }
			$order_info->order_name = $order_name;
            $order_info->landowners_detail = $landowners_detail;

            return $this->success($order_info);

        } catch(\Exception $e){
            DB::rollback();
            throw $e;
        }

	}

    /**
     * 确认支付
     * @param $user_id
     * @param $order_id
     * @param OrderService $orderService
     * @param OrderPingppService $orderPingppService
     * @return mixed
     */
    public function gotoPay($user_id,$order_id,LandownersOrderService $landownersOrderService,OrderPingppService $orderPingppService)
    {
        //支付类型
        $pay_channel = Input::get('pay_channel','');

        //是否需要全部的返回数据
        $needs_full = Input::get('needs_full',0);

        if(!$user_id){
            return $this->failure('请先登录');
        }

        if (!$order_id)
        {
            return $this->failure('未找到订单');
        }

        if (!$pay_channel)
        {
            return $this->failure('请选择支付方式');
        }

        $order_info  =  $landownersOrderService->getOrderInfo($user_id,$order_id);

        if (empty($order_info))
        {
            return $this->failure('未找到订单');
        }

    	/* 订单有效性判断 */
        if ($order_info->status != LANDOWNERS_ORDER_PENDING)
        {
            return $this->failure('该订单不可支付');
        }

        if($order_info->buyer_id != $user_id ){
            return $this->failure('无权操作该订单');
        }
        //如果库存不足，则支付失败
        foreach($order_info->landownersOrderEvaluation as $item){
            if($item->quantity > $item->landownersSpec->stock){
                return $this->failure('库存不足，无法支付，请重新下单');
            }
        }

        $checkChennelData = $orderPingppService->checkChennel($pay_channel);
        if(!$checkChennelData['result']){
            return $this->failure($checkChennelData['msg']);
        }

        $channel = $checkChennelData['data'];
        //获取支付para
        $payparaData = $orderPingppService->getPayPara($user_id,$order_id,$order_info->seller_name,$order_info->order_sn,$order_info->order_amount,$pay_channel,$needs_full);
        if(!$payparaData['result']){
            return $this->failure($payparaData['msg']);
        }

        /* 保存支付方式 */

        $order_info->payment_id = $channel->payment_id;
        $order_info->payment_code = $channel->payment_code;
        $order_info->payment_name = $channel->payment_name;

        $order_info->save();

        return $this->success($payparaData['data']);
    }

    /**
     * 买家取消订单
     * @param $user_id 用户id
     * @param $id：订单id
     * @return mixed
     * @throws Exception
     * @throws \Exception
     */
    public function cancel($user_id,$id=0){

        if(!$id){
            return $this->failure('参数不对');
        }

        $user_info = DB::table('member')->where('user_id',$user_id)->first();

        $orderService = new LandownersOrderService();

        //只有待付款的订单可以取消
        $order_info = $orderService->getOrderInfo($user_id,$id);

        if (empty($order_info)){
            return $this->failure('参数不对');
        }

//        if($order_info->tuan_id > 0){
//            return $this->failure('团购订单不可取消');
//        }

        if($order_info->status!=LANDOWNERS_ORDER_PENDING ){
            return $this->failure('该订单无法取消订单');
        }

        if(count($order_info->landownersRefund)>0){
            foreach($order_info->landownersRefund as $k => $item){
                if($item->refund_status != LANDOWNERS_ORDRE_REFUND && $item->refund_status != LANDOWNERS_REFUND_CANCELED ){
                    return $this->failure('请在退款/货流程结束后再取消订单！');
                }
            }
        }

        DB::beginTransaction();

        try {
            $order_info->status = LANDOWNERS_ORDRE_CANCELED;		//0表示订单为取消状态

            /* 更新订单状态 */
            $order_info->save();

//            //加上订单使用掉的优惠券次数
//            if($order_info->coupon_sn){
//                DB::table('coupon_sn')->where('coupon_sn',$order_info->coupon_sn)->increment('remain_times',1);
//            }

//            /* 加回商品库存 */ 库存减少修改在支付成功后进行 所以现在无库存变化
//            $orderService->changeStock('+',$id);

            /* 添加订单操作日志 订单从代付款->已取消 */
            $orderService->addLandownersOrderLog($id,$user_info->user_name,LANDOWNERS_ORDER_PENDING,LANDOWNERS_ORDRE_CANCELED,"买家取消订单",'','');

            /* 发送给卖家订单取消通知 */
            //todo

            DB::commit();

            return $this->success(null);

        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }

    /**
     *    删除订单
     *
     *    @author    Garbin
     *    @return    void
     */
    function delete($user_id,$id=0)
    {

        if(!$id){
            return $this->failure('参数不对');
        }

        $user_info = DB::table('member')->where('user_id',$user_id)->first();

        $orderService = new LandownersOrderService();

        //只有待付款的订单可以取消
        $order_info = $orderService->getOrderInfo($user_id,$id);

        if (empty($order_info)){
            return $this->failure('参数不对');
        }

        /* 只有已取消或者已退款或者已完成的订单可以删除 */
        if($order_info->status!=LANDOWNERS_ORDRE_CANCELED && $order_info->status!=LANDOWNERS_ORDRE_REFUND && $order_info->status!=LANDOWNERS_ORDRE_FINISHED){
            return $this->failure('该订单不可删除');
        }

        DB::beginTransaction();

        try {
            //买家删除标志位 设置为true
            $order_info->delflg_buyer = ORDER_DELETE_NOTE;

            $order_info->save();

            /* 添加订单操作日志 订单->已删除 */
            $orderService->addLandownersOrderLog($id,$user_info->user_name,$order_info->status,LANDOWNERS_ORDER_DELETED,"买家删除订单",'','');

            return $this->success(null);
        } catch (Exception $e) {
            DB::rollback();
            throw $e;
        }
    }

    //评价
    public function postEvaluate($user_id,$id){

        if($id == 0){
            return $this->failure('参数不对');
        }

        $orderService = new LandownersOrderService();
        //订单基本信息
        $order_info = $orderService->getOrderInfo($user_id,$id);

        if(!$order_info){
            return $this->failure("该订单不存在");
        }

        if($order_info->status != LANDOWNERS_ORDRE_FINISHED){
            return $this->failure("该订单不可评价");
        }

        if($order_info->evaluation_status == EVALUATE_YES){
            return $this->failure("该订单已评价过，不可重复评价");
        }
        foreach ($order_info->landownersOrderEvaluation as $i => $order_goods){
            $rec_id_arr[] = $order_goods->rec_id;//订单商品
        }
//
        $evaluation_arr = Input::get("evaluation");//星级
        if(!$evaluation_arr){
            return $this->failure("评分不能为空！");
        }
        $comment_arr = Input::get("comment");//评论
        $evaluation_images_arr = Input::get('evaluation_images');
        $anonymous = Input::get("anonymous",0);//是否匿名
        //上传评论图片
        $evaluation_images = '';

        if($evaluation_images_arr && count($evaluation_images_arr)>0){
            if(count($evaluation_images_arr)>0){
                foreach($evaluation_images_arr as $i => $image){
                    $temps = explode(',',$image);
                    $img = base64_decode($temps[1]);
                    $filepath = '/data/landsevaluation/'.$id.'/' ;
                    $filename = $filepath . $i . '_'.gmtime() . '.jpg';
                    Storage::disk()->put($filename,$img);
                    $evaluation_images[]=$filename;
                }
            }else{
                $evaluation_images='';
            }
        }else{
            $evaluation_images='';
        }

        //更新商品评论
        if(is_array($rec_id_arr)) {
            foreach ($rec_id_arr as $rec_id) {
                $ordergoods = LandownersOrderEvaluation::find($rec_id);
                $ordergoods->evaluation = $evaluation_arr;
                $ordergoods->comment = $comment_arr;
                $ordergoods->evaluation_time = gmtime();
                $ordergoods->evaluation_image = count($evaluation_images)> 0 ? json_encode($evaluation_images):'';
                $ordergoods->save();
            }
        }
        $order_info->evaluation_status = EVALUATE_YES;
        $order_info->evaluation_time = gmtime();
        $order_info->anonymous = $anonymous;

        $order_info->save();
        //更新评分
        $gpa = DB::table('landowners_order_evaluation')
            ->leftJoin('landowners_order', 'landowners_order_evaluation.order_id', '=', 'landowners_order.order_id')
            ->where('landowners_id',$ordergoods->landowners_id)
            ->where('landowners_order.evaluation_status',1)
            ->avg('evaluation');
        LandownersStatistics::where('landowners_id', $ordergoods->landowners_id)->increment('comments');
        LandownersStatistics::where('landowners_id', $ordergoods->landowners_id)->update(array('gpa'=>$gpa));
        //获取对应商品所在地区名称
        $landowners_info = DB::table('landowners')->where('landowners_id',$ordergoods->landowners_id)->first();
        //评论数据入库用于乡粉分享
        $full_evaluation = array(
            'item_id'  => $ordergoods->landowners_id,
            'user_id'  => $user_id,
            'evaluation_comment'    => $ordergoods->comment,
            'pictures'  => $ordergoods->evaluation_image,
            'evaluation_time'  => $ordergoods->evaluation_time,
            'evaluation_type'  => 'landowners',
            'item_name'=>$landowners_info->landowners_name,
            'province'=>$landowners_info->province,
            'city'=>$landowners_info->city,
            'country'=>$landowners_info->country,
        );
        DB::table('full_evaluation')->insert($full_evaluation);
        return $this->success(null);

    }

    /**
     *	取消退款/货
     *
     *  @param $rec_id：商品订单id
     */
    public function cancelRefund($user_id,$order_id){

        if(!$order_id){
            return $this->failure('参数不对');
        }

        $user_name = DB::table('member')->where('user_id',$user_id)->pluck('user_name')[0];

        $orderService = new LandownersOrderService();
        $orderInfo = $orderService->getOrderInfo($user_id,$order_id);

        //判断订单是否存在
        if(!$orderInfo){
            return $this->failure('订单不存在');
        }

        //订单状态不是待发货或者待收货，不可以提交退款/货申请
        if($orderInfo->status != LANDOWNERS_ORDER_REFUNDING){
            return $this->failure('该订单不可取消退款/货');
        }

        //判断订单商品是否存在
        $spec_id = 0;
        foreach($orderInfo->landownersOrderEvaluation as $order_goods){
            if($order_goods->order_id == $order_id){
                $spec_id = $order_goods->spec_id;
                break;
            }
        }
        if(!$spec_id){
            return $this->failure('订单商品不存在');
        }

        //判断该商品是否已经处于退款/货流程中了
        $refund_id = 0;
        if($orderInfo->landowners_refund_goods){
            foreach($orderInfo->landowners_refund_goods as $refund_goods){
                if($refund_goods->spec_id == $spec_id){
                    $refund_id = $refund_goods->refund_id;
                    break;
                }
            }
        }
        $orderRefund = null;
        if($refund_id){
            foreach($orderInfo->landowners_refund as $order_refund){
                if($order_refund->refund_id == $refund_id){
                    $orderRefund = $order_refund;
                    if($orderInfo->status == LANDOWNERS_ORDER_ACCEPTED){
                        //订单状态不是待发货且不是退款或者待收货且不是退货，则不可以提交退款/货申请
                        if(!($order_refund->refund_status == LANDOWNERS_REFUND_PENDING && $order_refund->refund_type == REFUND_TYPE_REFUND)){
                            return $this->failure('该订单不可取消退款');
                        }
                    }
                    if($orderInfo->status == LANDOWNERS_ORDRE_SHIPPED){
                        if(!(($order_refund->refund_status == LANDOWNERS_REFUND_PENDING || $order_refund->refund_status == LANDOWNERS_ORDER_ACCEPTED )&& $order_refund->refund_type == REFUND_TYPE_RETURN_GOODS)){
                            return $this->failure('该订单不可取消退货申请');
                        }
                    }
                }
            }
        }

        DB::beginTransaction();

        try{
            //取消退款申请
            $orderRefund->refund_status = LANDOWNERS_REFUND_CANCELED;
            $orderRefund->save();

            //添加记录
            $refundService = new LandownersRefundService();
            $remark = "用户取消退款申请";
            $refundService->addOrderRefundLog($refund_id,$user_name,$orderRefund->refund_type,LANDOWNERS_REFUND_PENDING,LANDOWNERS_REFUND_CANCELED,$remark);
            //订单操作记录
            DB::table('landowners_order')
                ->where('order_id',$order_id)
                ->update([
                    'status' => LANDOWNERS_ORDER_ACCEPTED,//待出行
                ]);
            /* 操作记录 */
            $orderService->addLandownersOrderLog($order_id,$user_name,LANDOWNERS_ORDER_REFUNDING,LANDOWNERS_ORDER_ACCEPTED,'用户取消退款','','');
            DB::commit();
            return $this->success(null);
        }catch(Exception $e){
            DB::rollback();
            throw $e;
        }

    }

    //投诉
    public function complain($user_id,$id, LandownersOrderService $landownersOrderService){
        if(!$user_id){
            return $this->failure('请先登录');
        }
        if(!$id){
            return $this->args_invalid();
        }

        $link_name = Input::get('link_name');
        $link_phone = Input::get('link_phone');

        if(!$link_name){
            return $this->failure('请填写联系人');
        }

        if(!$link_phone){
            return $this->failure('请填写联系号码');
        }

        if(!is_mobile($link_phone)){
            return $this->failure('请填写正确的手机号码');
        }

        $comment = Input::get("comment");//描述

        $complain_images_arr = Input::get('complain_images');
        //处理上传的图片
        $complain_images = [];
        if(count($complain_images_arr)>0){
            foreach($complain_images_arr as $i => $image){
                $temps = explode(',',$image);
                $img = base64_decode($temps[1]);
                $filepath = '/data/landowners_complain/' . local_date_ymd(gmtime()) .'/' ;
                $filename = $filepath . 'complain_'.$i.'_'.gmtime() .'.jpg';
                Storage::disk()->put($filename,$img);
                $complain_images[]=$filename;
            }
        }

     $landownersOrderService->complainLandownersOrder($user_id,$id,$link_name,$link_phone,$comment,$complain_images,'landowners',true);

    }
    //ADd 获取快递公司对应英文名
    public function getShippingEg($shipping)
    {
        switch ($shipping){
            case "EMS经济快递"://后台中显示的快递公司名称
                $postcom = 'ems';//快递公司代码
                break;
            case "EMS":
                $postcom = 'ems';
                break;
            case "邮政快递包裹":
                $postcom = 'ems';
                break;
            case "申通快递":
                $postcom = 'shentong';
                break;
            case "圆通速递":
                $postcom = 'yuantong';
                break;
            case "顺丰速递":
                $postcom = 'shunfeng';
                break;
            case "天天快递":
                $postcom = 'tiantian';
                break;
            case "韵达快递":
                $postcom = 'yunda';
                break;
            case "中通快递":
                $postcom = 'zhongtong';
                break;
            case "龙邦快递":
                $postcom = 'longbanwuliu';
                break;
            case "宅急送":
                $postcom = 'zhaijisong';
                break;
            case "全一快递":
                $postcom = 'quanyikuaidi';
                break;
            case "汇通速递":
                $postcom = 'huitongkuaidi';
                break;
            case "民航快递":
                $postcom = 'minghangkuaidi';
                break;
            case "亚风速递":
                $postcom = 'yafengsudi';
                break;
            case "快捷速递":
                $postcom = 'kuaijiesudi';
                break;
            case "华宇物流":
                $postcom = 'tiandihuayu';
                break;
            case "中铁快运":
                $postcom = 'zhongtiewuliu';
                break;
            /* 修改 by www.68ecshop.com start */
            case "百世汇通":
                $postcom = 'huitongkuaidi';
                break;
            case "全峰快递":
                $postcom = 'quanfengkuaidi';
                break;
            case "德邦":
                $postcom = 'debangwuliu';
                break;
            /* 修改 by www.68ecshop.com end */
            case "FedEx":
                $postcom = 'fedex';
                break;
            case "UPS":
                $postcom = 'ups';
                break;
            case "DHL":
                $postcom = 'dhl';
                break;
            default:
                $postcom = '';
        }
        return $postcom;
    }

}
